package com.kcht.np.controller;

import com.kcht.np.util.JsonResult;
import com.kcht.np.util.JsonUtils;
import lombok.SneakyThrows;
import org.apache.http.Header;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.ByteArrayInputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;

public class HttpExecutor {

    @SneakyThrows
    public static JsonResult get(String uri, Header... headers){
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet get=new HttpGet();
        get.setURI(new URI(uri));
        get.addHeader("content-type","application/json");
        if(headers!=null){
            for (Header header : headers) {
                get.addHeader(header);
            }
        }
        return JsonUtils.jsonToPojo(client.execute(get).getEntity().getContent().toString(), JsonResult.class);
    }

    @SneakyThrows
    public static JsonResult post(String uri,String content, Header... headers){
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post=new HttpPost();
        post.setURI(new URI(uri));
        post.addHeader("content-type","application/json");
        if(headers!=null){
            for (Header header : headers) {
                post.addHeader(header);
            }
        }
        BasicHttpEntity entity=new BasicHttpEntity();
        entity.setContent(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)));
        post.setEntity(entity);
        return JsonUtils.jsonToPojo(client.execute(post).getEntity().getContent().toString(), JsonResult.class);
    }
}